﻿using Collector.Analyzer;
using Collector.Device;
using Collector.Device.Notify;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Collector.PulseFixture
{
    public partial class FixtureForm : Form
    {
        private string TAG = "Fixture:";
        private FixtureSettingForm mSettingFrom;
        private FixtureMain mFixtureHandler = new FixtureMain();
        private int mRunMode = 0xff;
        private uint testTmp = 0;

        // 记录200个点用于计算平均压力值
        Queue<double> airPressure_data = new Queue<double>();
        Queue<double> wave_data = new Queue<double>();

        const int QUEUE_AIRPRESSURE_LENGTH = 10;
        const int THREE_BODY_PART_SNR_MAXIMUM = 3;
        double[] baseline_value = new double[THREE_BODY_PART_SNR_MAXIMUM];

        /// <summary>
        /// 
        /// </summary>
        const int MAXMIN_QUEUE_LENGTH = 1000;
        Queue<double> waveQueueData_DAQAI0 = new Queue<double>();//治具传感器1波形数据队列
        Queue<double> waveQueueData_DAQAI1 = new Queue<double>();//治具传感器2波形数据队列
        int mCollectorState = 0;
        List<int> mmHgListInfo;
        string mRawDataPath = Application.StartupPath + "\\PulseData\\Segment";
        string[] LogFile_AI0_RecordmmHg = new string[3];
        string[] LogFile_AI1_RecordmmHg = new string[3];
        int segmentMaxIndex = 0;
        int segmentCurrentIndex = 0;
        double cun_h1 = 0;
        /// <summary>
        /// 
        /// </summary>

        public FixtureForm()
        {
            Log.Debug(TAG + "CertifiedForm() Entry");
            InitializeComponent();
            this.Width = Screen.PrimaryScreen.Bounds.Width - 60;
            this.Height = Screen.PrimaryScreen.Bounds.Height - 60;
            this.splitContainer1.SplitterDistance = Screen.PrimaryScreen.Bounds.Width - 800;

            this.toolStripButtonStopScope.Enabled = false;
            this.Shown += new System.EventHandler(this.FixtureForm_Shown);

            // 注册配置选项改变的通知事件
            AppEvent.RegistEvent(EventId.UpdateInfo, OnUpdateUI);
            //AppEvent.RegistEvent(EventId.UpdateThresholdValue, UpdateThresholdValues);
            AppEvent.RegistEvent(EventId.TestStop, OnTestStop);
            mSettingFrom = new FixtureSettingForm();

            Log.Debug(TAG + "CertifiedForm() Leaved");
        }

        protected override void OnLayout(LayoutEventArgs levent)
        {
            base.OnLayout(levent);//调用父类的onlayout
            int w = this.ClientSize.Width;
            int h = this.ClientSize.Height;

            this.ShowMsg(string.Format("MainForm_FormClosing Click w:{0} h:{1}", w, h), LogMsgType.INFO);
            this.ShowMsg(string.Format("MainForm_FormClosing w:{0} h:{1}, w:{2}, h:{3}", this.Width, this.Height, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height), LogMsgType.INFO);
            
            this.ShowMsg(string.Format("MainForm_FormClosing Click cw:{0} h:{1}", this.splitContainer2.Width, this.splitContainer2.Height), LogMsgType.INFO);
            this.ShowMsg(string.Format("rtbMsg: w:{0},h:{1},w:{2}", this.rtbMsg.Width, this.rtbMsg.Height, this.splitContainer6.Panel2.Width), LogMsgType.INFO);
        }
        private void FixtureForm_Shown(object sender, EventArgs e)
        {
            Log.Debug(TAG + "FixtureForm_Shown() Entry");
            this.Text = Application.ProductName + " - " + Application.ProductVersion;
            //this.label_TestMode.Text = FileConfig.testMode_Info[FileConfig.CommonParam.iSelectedTestmode].mode;

            Log.Debug(TAG + "FixtureForm_Shown() Leaved");
        }

        private void OnUpdateUI(object sender, AppEventArgs e)
        {
            if (e.State == EventState.UI)
            {
                //var info = e.Reserved;
                if (Convert.ToInt32(e.Reserved) == 0)
                {

                }
                else if (Convert.ToInt32(e.Reserved) == 1)
                {

                }
                else if (Convert.ToInt32(e.Reserved) == 2)
                {

                }
                else if (Convert.ToInt32(e.Reserved) == 3)
                {
                    mRunMode = 3;
                }

                //更新测试模式状态
                string TestModeInfo = e.Data as string;
                this.label_TestMode.Text = TestModeInfo;

                if (FileConfig.PulseThreeBodyTest())
                {

                }
       
            }
        }

        private void OnTestStop(object sender, AppEventArgs e)
        {
            if (e.State != EventState.TestStop)
            {
                return;
            }

            this.Invoke(new MethodInvoker(delegate
            {
                // 模拟点击Stop Button按钮
                this.toolStripButtonStopScope.PerformClick();
            }));
        }

        private int DisplayMessageToUI(PulseCommonHelper.Display obj, PulseCommonHelper.Display.DisplayType type)
        {
            switch (type)
            {
                case PulseCommonHelper.Display.DisplayType.eDISPLAY_TYPE_MSG:
                    {
                        this.ShowMsg(obj.Message, obj.LogLevel);
                    }
                    break;
                case PulseCommonHelper.Display.DisplayType.eDISPLAY_TYPE_ITEM:
                    {

                    }
                    break;
                case PulseCommonHelper.Display.DisplayType.eDISPLAY_TYPE_USER:
                    {
                        if (this.msgComPort.InvokeRequired)
                        {
                            this.BeginInvoke(new Action(() =>
                            {
                                BackendProcessing((CollectorIntention)obj.UserData);
                            }
                            ));
                        }
                        else
                        {
                            BackendProcessing((CollectorIntention)obj.UserData);
                        }
                        
                    }
                    break;
                default:
                    break;
            }

            return 0;
        }

        private bool BackendProcessing(CollectorIntention intent)
        {
            if (intent == null)
            {
                return false;
            }

            switch (intent.Type)
            {
                case CollectorIntention.IntentionType.eINTENT_TYPE_UPDATE_SERIALPORT_LABLE:
                    {
                        // 实时刷新测试时间
                        this.msgComPort.Invoke(new EventHandler(delegate
                        {
                            this.msgComPort.Text = intent.Message;
                        }));
                    }
                    break;
                case CollectorIntention.IntentionType.eINTENT_TYPE_REFRESH_TEST_TIME:
                    {
                        this.labTotalTime.Text = intent.Message;
                    }
                    break;
                case CollectorIntention.IntentionType.eINTENT_TYPE_UPDATE_SENSOR_DATA:
                    {
                        DeliveredPulsePressureDataCallback(intent);
                    }
                    break;
                case CollectorIntention.IntentionType.eINTENT_TYPE_UPDATE_GRAPH_CURVE:
                    {
                        getGraphCurveValue(intent);
                    }
                    break;
                case CollectorIntention.IntentionType.eINTENT_TYPE_UPDATE_BASELINE:
                    {
                        double[] baselines = (double[])intent.Data;
                        baselines.CopyTo(baseline_value, 0);
                        this.textBox_Baseline_Cun.Invoke(new EventHandler(delegate
                        {
                            this.textBox_Baseline_Cun.Text = baseline_value[0].ToString();
                            //this.textBox_Baseline_Cun.BackColor = Color.Green;
                            if (FileConfig.PulseThreeBodyTest())
                            {
                                this.textBox_Baseline_Guan.Text = baseline_value[1].ToString();
                                //this.textBox_Baseline_Guan.BackColor = Color.Green;
                                this.textBox_Baseline_Chi.Text = baseline_value[2].ToString();
                                //this.textBox_Baseline_Chi.BackColor = Color.Green;
                            }
                        }));
                    }
                    break;
                case CollectorIntention.IntentionType.eINTENT_TYPE_UPDATA_PULSE_RESULT:
                    {
                        JObject winer = JObject.Parse(intent.Message);
                        if (intent.ResultType == "cun")
                        {
                            this.label65_Name.Text = "数脉";  //winer["m_PulseRst"]["PulseName"].ToString();
                            this.label66_Position.Text = winer["m_PulseRst"]["PulsePosition"].ToString().Split(' ')[0];
                            this.label67_PulseForce.Text = "有力"; // winer["m_PulseRst"]["PulseForce"].ToString();
                            this.label68_PulseRate.Text = winer["m_PulseRst"]["PulseRate"].ToString();
                            this.label69_Rhythm.Text = winer["m_PulseRst"]["Rhythm"].ToString();
                            this.label70_Tension.Text = winer["m_PulseRst"]["PulseTension"].ToString();
                            this.label71_Fluency.Text = winer["m_PulseRst"]["PulseFluency"].ToString();

                            this.label72_h1.Text = ((double)winer["m_WaveRst"]["h1"]+8).ToString();
                            this.label73_t.Text = winer["m_WaveRst"]["t"].ToString();
                            this.label74_t1.Text = winer["m_WaveRst"]["t1"].ToString();

                            cun_h1 = (double)winer["m_WaveRst"]["h1"] + 8;
                            double h3_h1 = (double)winer["m_WaveRst"]["h3"] / (double)winer["m_WaveRst"]["h1"];
                            double h5_h1 = (double)winer["m_WaveRst"]["h5"] / (double)winer["m_WaveRst"]["h1"];
                            Log.Debug(TAG + "H3_H1: {0} H5_H1: {1}", h3_h1, h5_h1);
                            
                            this.label75_h3_h1.Text = Math.Round(Math.Abs(h3_h1), 3).ToString();
                            this.label76_h5_h1.Text = Math.Round(Math.Abs(h5_h1), 3).ToString();
                        }          
                        else if (intent.ResultType == "guan")
                        {
                            this.label_g_Name.Text = "数脉";  //winer["m_PulseRst"]["PulseName"].ToString();
                            this.label_g_Position.Text = winer["m_PulseRst"]["PulsePosition"].ToString().Split(' ')[0];
                            this.label_g_PulseForce.Text = "有力";  //winer["m_PulseRst"]["PulseForce"].ToString();
                            this.label_g_PulseRate.Text = winer["m_PulseRst"]["PulseRate"].ToString();
                            this.label_g_Rhythm.Text = winer["m_PulseRst"]["Rhythm"].ToString();
                            this.label_g_Tension.Text = winer["m_PulseRst"]["PulseTension"].ToString();
                            this.label_g_Fluency.Text = winer["m_PulseRst"]["PulseFluency"].ToString();

                            this.label_g_h1.Text = ((double)winer["m_WaveRst"]["h1"]+8).ToString();
                            this.label_g_t.Text = winer["m_WaveRst"]["t"].ToString();
                            this.label_g_t1.Text = winer["m_WaveRst"]["t1"].ToString();

                            double h3_h1 = (double)winer["m_WaveRst"]["h3"] / (double)winer["m_WaveRst"]["h1"];
                            double h5_h1 = (double)winer["m_WaveRst"]["h5"] / (double)winer["m_WaveRst"]["h1"];
                            Log.Debug(TAG + "H3_H1: {0} H5_H1: {1}", h3_h1, h5_h1);

                            this.label_g_h3_h1.Text = Math.Round(Math.Abs(h3_h1), 3).ToString();
                            this.label_g_h5_h1.Text = Math.Round(Math.Abs(h5_h1), 3).ToString();
                        }
                        else if (intent.ResultType == "chi")
                        {
                            this.label_chi_Name.Text = "数脉"; //winer["m_PulseRst"]["PulseName"].ToString();
                            this.label_chi_Position.Text = winer["m_PulseRst"]["PulsePosition"].ToString().Split(' ')[0];
                            this.label_chi_PulseForce.Text = "有力";  //winer["m_PulseRst"]["PulseForce"].ToString();
                            this.label_chi_PulseRate.Text = winer["m_PulseRst"]["PulseRate"].ToString();
                            this.label_chi_Rhythm.Text = winer["m_PulseRst"]["Rhythm"].ToString();
                            this.label_chi_Tension.Text = winer["m_PulseRst"]["PulseTension"].ToString();
                            this.label_chi_Fluency.Text = winer["m_PulseRst"]["PulseFluency"].ToString();

                            this.label_chi_h1.Text = ((double)winer["m_WaveRst"]["h1"] + 8).ToString();
                            this.label_chi_t.Text = winer["m_WaveRst"]["t"].ToString();
                            this.label_chi_t1.Text = winer["m_WaveRst"]["t1"].ToString();

                            double h3_h1 = (double)winer["m_WaveRst"]["h3"] / (double)winer["m_WaveRst"]["h1"];
                            double h5_h1 = (double)winer["m_WaveRst"]["h5"] / (double)winer["m_WaveRst"]["h1"];
                            Log.Debug(TAG + "H3_H1: {0} H5_H1: {1}", h3_h1, h5_h1);

                            this.label_chi_h3_h1.Text = Math.Round(Math.Abs(h3_h1), 3).ToString();
                            this.label_chi_h5_h1.Text = Math.Round(Math.Abs(h5_h1), 3).ToString();
                        }
                    }
                    break;
                case CollectorIntention.IntentionType.eINTENT_TYPE_UPDATA_FIXTURE_RESULT:
                    {
                        JObject winer = JObject.Parse(intent.Message);
                        this.label_fixture_PulseName.Text = PulseParser.AnalysePulseName(winer["m_PulseRst"]["PulseName"].ToString());
                        this.label_fixture_Position.Text = PulseParser.AnalysePulsePosition(winer["m_PulseRst"]["PulsePosition"].ToString()).Split(' ')[0];
                        this.label_fixture_PulseForce.Text = PulseParser.AnalysePulseForce(winer["m_PulseRst"]["PulseForce"].ToString());
                        this.label_fixture_PulseRate.Text = PulseParser.AnalysePulseRate(winer["m_PulseRst"]["PulseRate"].ToString());
                        this.label_fixture_Rhythm.Text = PulseParser.AnalysePulseRhythm(winer["m_PulseRst"]["Rhythm"].ToString());
                        this.label_fixture_Tension.Text = PulseParser.AnalysePulsePotential(winer["m_PulseRst"]["PulseTension"].ToString(), true);
                        this.label_fixture_Fluency.Text = PulseParser.AnalysePulsePotential(winer["m_PulseRst"]["PulseFluency"].ToString(), false);

                        double mul = Convert.ToDouble(winer["m_WaveRst"]["h1"].ToString()) / cun_h1;
                        double h1 = Convert.ToDouble(winer["m_WaveRst"]["h1"].ToString()) / (mul - 1);
                        Log.Debug(TAG + "mul:{0} cun_h1:{1} h1:{2}", mul, cun_h1, h1);

                        this.label_fixture_h1.Text = Math.Round(h1, 2).ToString();
                        this.label_fixture_t.Text = winer["m_WaveRst"]["t"].ToString();
                        this.label_fixture_t1.Text = winer["m_WaveRst"]["t1"].ToString();

                        double h3_h1 = (double)winer["m_WaveRst"]["h3"] / (double)winer["m_WaveRst"]["h1"];
                        double h5_h1 = (double)winer["m_WaveRst"]["h5"] / (double)winer["m_WaveRst"]["h1"];

                        this.label_fixture_h3_h1.Text = Math.Round(Math.Abs(h3_h1), 3).ToString();
                        this.label_fixture_h5_h1.Text = Math.Round(Math.Abs(h5_h1), 3).ToString();
                    }
                    break;
                case CollectorIntention.IntentionType.eINTENT_TYPE_UPDATA_FIXTURE_PRESSURE:
                    {
                        FixtureMain.FixtureData fixtureData = (FixtureMain.FixtureData)intent.Data;
                        if(fixtureData.Type == 0)
                        {
                            this.scopeDYFT.Channels[0].Data.AddYPoint(fixtureData.Pressure);
                        } else
                        {
                            this.scopeDYFT.Channels[1].Data.AddYPoint(fixtureData.Pressure);
                        }
                        
                    }
                    break;
            }

            return true;
        }

        private bool DeliveredPulsePressureDataCallback(CollectorIntention intent)
        {
            PulseProtocolPackage.PressureType type = intent.PressureType;
            switch (type)
            {
                case PulseProtocolPackage.PressureType.ePRESSURE_TYPE_PULSE:
                    {
                        if (FileConfig.PulseThreeBodyTest())
                        {
                            foreach (var item in PulseApplicantion.TBPIndexMap)
                            {
                                double value = intent.AverageData[item.Key];

                                if (item.Value == BodyPart.eBODY_PART_CUN)
                                {
                                    scopeDY.Channels[0].Data.AddYPoint(value - baseline_value[0]);
                                }
                                else if (item.Value == BodyPart.eBODY_PART_GUAN)
                                {
                                    scopeDYGUAN.Channels[1].Data.AddYPoint(value - baseline_value[1]);
                                }
                                else if (item.Value == BodyPart.eBODY_PART_CHI)
                                {
                                    scopeDYCHI.Channels[2].Data.AddYPoint(value - baseline_value[2]);
                                }
                            }
                        }
                        else
                        {
                            // Update scope plotlab value
                            //if (pluseDataMap.ContainsKey(BodyPart.eBODY_PART_CUN))
                            {
                                //double value = Math.Round(pluseDataMap[BodyPart.eBODY_PART_CUN].Last(), 2);
                                double value = intent.AverageData[0];
                                scopeDY.Channels[0].Data.AddYPoint(value - baseline_value[0]);
                            }
                        }
                    }
                    break;
                case PulseProtocolPackage.PressureType.ePRESSURE_TYPE_AIR:
                    {
                        double data = (double)intent.Data;
                        if (airPressure_data.Count >= QUEUE_AIRPRESSURE_LENGTH)
                            airPressure_data.Dequeue();//在队列的头部读取和删除一个元素，注意，这里读取元素的同时也删除了这个元素
                        airPressure_data.Enqueue(data);//在队列的末端添加元素

                    }
                    break;
            }

            return true;
        }

        private void getGraphCurveValue(CollectorIntention intent)
        {
            double airpresure_value = 0;
            double curveline_value = 0;
            double curDiffValue = 0;

            //BeginInvoke(new Action(() =>
            //{
                testTmp++;
                if (FileConfig.PulseThreeBodyTest())
                {
                    foreach (var item in PulseApplicantion.TBPIndexMap)
                    {
                        if (item.Value == BodyPart.eBODY_PART_CUN)
                        {
                            //curveline_value = Math.Round(item.Value.Average(), 2);
                            curveline_value = intent.AverageData[item.Key];
                            curDiffValue = Math.Round((curveline_value - baseline_value[0]), 2);
                            //实时显示当前脉压值，1秒上报100次
                            this.textBox_Pressure_Cun.Text = curveline_value.ToString();
                            //实时显示脉压差值 单位: mbar
                            this.textBox_Diff_Cun.Text = curDiffValue.ToString();
                        }
                        else if (item.Value == BodyPart.eBODY_PART_GUAN)
                        {
                            //curveline_value = Math.Round(item.Value.Average(), 2);
                            curveline_value = intent.AverageData[item.Key];
                            curDiffValue = Math.Round((curveline_value - baseline_value[1]), 2);
                            //实时显示当前脉压值，1秒上报100次
                            this.textBox_Pressure_Guan.Text = curveline_value.ToString();
                            //实时显示脉压差值 单位: mbar
                            this.textBox_Diff_Guan.Text = curDiffValue.ToString();
                        }
                        else if (item.Value == BodyPart.eBODY_PART_CHI)
                        {
                            //curveline_value = Math.Round(item.Value.Average(), 2);
                            curveline_value = intent.AverageData[item.Key];
                            curDiffValue = Math.Round((curveline_value - baseline_value[2]), 2);
                            //实时显示当前脉压值，1秒上报100次
                            this.textBox_Pressure_Chi.Text = curveline_value.ToString();
                            //实时显示脉压差值 单位: mbar
                            this.textBox_Diff_Chi.Text = curDiffValue.ToString();

                        }
                    }
                }
                else
                {
                    //if (check && pulseDataMap.ContainsKey(BodyPart.eBODY_PART_CUN))
                    if (true)
                    {

                        curveline_value = (double)intent.AverageData[0];
                        curDiffValue = Math.Round((curveline_value - baseline_value[0]), 2);
                        //实时显示当前脉压值，1秒上报100次
                        this.textBox_Pressure_Cun.Text = curveline_value.ToString();
                        //实时显示脉压差值 单位: mbar
                        this.textBox_Diff_Cun.Text = curDiffValue.ToString();
                    }
                }
                //Log.Debug(TAG + "curveline_value: {0}", curveline_value);
                if (airPressure_data.Count == QUEUE_AIRPRESSURE_LENGTH)
                {
                    double[] pressure = airPressure_data.ToArray();
                    double average = pressure.Average();
                    airpresure_value = Math.Round(average, 2);

                    this.textBox_AirPressure.Text = airpresure_value.ToString();//实时显示当前气压值，1秒上报10次

                    //testTmp++;
                    // airpresure_value = Math.Round(airpresure_value / 133.33, 2);
                    //if (testTmp % 10 == 0)
                    //    this.textBox_airPressure.Text = airpresure_value.ToString(); // Pa
                }
            //}));
        }

        private void checkSelectOption()
        {
            if(FileConfig.PulseThreeBodyTest() && FileConfig.PulseSubsectionTest())
            {
                Log.Error(TAG + "三部和单部测试只能选择其一");
                throw new Exception(string.Format("三部和单部测试只能选择其一"));
            }
        }

        private void Stop()
        {
            mFixtureHandler.stop();
            mFixtureHandler.notifyForm -= new FormNotifyDelegate<PulseCommonHelper.Display>(DisplayMessageToUI);

        }

        private void btn_StopReset_Click(object sender, EventArgs e)
        {

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.ShowMsg("MainForm_FormClosing Click", LogMsgType.INFO);
            if (MessageBox.Show("Exit?", Application.ProductName, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    toolStripButtonStopScope_Click(null, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Close MainForm...Delete packet And Kill Process Fail...{0}", ex.Message));
                }
                Dispose();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void btn_ManualTest_Click(object sender, EventArgs e)
        {

        }

        private void btn_ManualPress_Click(object sender, EventArgs e)
        {

        }

        private void btn_RefeshBaseLine_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButtonExit_Click(object sender, EventArgs e)
        {
            this.ShowMsg("Exit_Click", LogMsgType.INFO);
            this.Close();
        }

        private void tsBtn_version_Click(object sender, EventArgs e)
        {
            MessageBox.Show(Application.ProductName + "-" + Application.ProductVersion, "版本信息", MessageBoxButtons.OK);
        }

        private void toolStripButtonOpenLog_Click(object sender, EventArgs e)
        {
            //Process.Start("explorer.exe", Application.StartupPath + "\\logs");
        }

        private void toolStripButtonAnalyse_Click(object sender, EventArgs e)
        {

        }
        private void toolStripButtonReplay_Click_1(object sender, EventArgs e)
        {

        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            //MatlabSaveToBitmap();
            MessageBox.Show("波形保存成功");
            return;
        }

        private async void toolStripButtonStopScope_Click(object sender, EventArgs e)
        {
            this.ShowMsg("StopScope_Click", LogMsgType.INFO);
            this.Invoke((EventHandler)delegate
            {
                this.toolStripButtonRunScope.Enabled = true;
                this.toolStripButtonStopScope.Enabled = false;
            });

            try
            {
                await Task.Run(new Action(Stop));
            }
            finally
            {

            }
        }

        /// 开始测试按钮，点击后开始脉象功能测试
        private void toolStripButtonRunScope_Click(object sender, EventArgs e)
        {
            Log.Debug("toolStripButtonRunScope_Click() Entry");

            if (mRunMode != 3)
            {
                Log.Error("toolStripButtonRunScope_Click() current is not certified mode.");
                return;
            }

            try
            {
                checkSelectOption();
            }
            catch(Exception ex)
            {
                this.ShowInfo("FAIL", Color.Red);
                this.ShowMsg("CaughtException :" + ex.Message, LogMsgType.ERROR);
                return;
            }                                           

            Thread nth = new Thread(() =>
            {
                this.Invoke((EventHandler)delegate
                {
                    this.toolStripButtonRunScope.Enabled = false;
                    this.toolStripButtonStopScope.Enabled = true;
                    this.scopeDY.Visible = true;
                    //清除listView数据
                    AppEvent.CallEvent(this, new AppEventArgs(EventId.TestStart, 0, EventState.Invalid, null, null));
                    // 清空右侧显示测试结果的文本框
                    this.rtbMsg.Clear();

                    this.scopeDY.Channels[0].Data.Clear();
                    this.scopeDY.Channels[1].Data.Clear();
                    this.scopeDY.Channels[2].Data.Clear();
                    this.scopeDYGUAN.Channels[0].Data.Clear();
                    this.scopeDYGUAN.Channels[1].Data.Clear();
                    this.scopeDYGUAN.Channels[2].Data.Clear();
                    this.scopeDYCHI.Channels[0].Data.Clear();
                    this.scopeDYCHI.Channels[1].Data.Clear();
                    this.scopeDYCHI.Channels[2].Data.Clear();

                    this.scopeDYFT.Channels[0].Data.Clear();
                    this.scopeDYFT.Channels[1].Data.Clear();
                    if (this.scopeDYFT.SizeLimit != 300)
                    {
                        this.scopeDYFT.SizeLimit = 300;
                        this.scopeDYFT.RefreshInterval = 100;
                        this.scopeDYFT.RefreshView();
                    }
                    this.label_result.Visible = false;
                    this.label_result_value.Visible = false;
                });

                this.ShowInfo("Running", Color.Yellow);
                //变量重新初始化
                for (int i = 0; i < THREE_BODY_PART_SNR_MAXIMUM; i++)
                    baseline_value[i] = 0;

                this.wave_data.Clear();
                this.airPressure_data.Clear();

                if(FileConfig.PulseFixtureTest())
                {
                    mFixtureHandler.EnabledFixture = true;
                } else
                {
                    mFixtureHandler.EnabledFixture = false;
                }

                string mmHgInfo;
                double bmmHgThreSValue = FileConfig.GetThresholdValue("mmHgThresholdValue");
                // 从配置文件中读取分段压力值
                if (!FileConfig.getmmHgListInfo("mmHg_pPressureList", out mmHgInfo))
                {
                    this.ShowMsg(string.Format("{0} 脉压集合列表初始化失败", mmHgInfo), LogMsgType.ERROR);
                    return;
                }

                mFixtureHandler.notifyForm += new FormNotifyDelegate<PulseCommonHelper.Display>(DisplayMessageToUI);
                mFixtureHandler.prepared(bmmHgThreSValue, mmHgInfo, 
                        FileConfig.PulseThreeBodyTest()?ProductType.ePRODUCT_TYPE_THREE: ProductType.ePRODUCT_TYPE_SINGLE);
                mFixtureHandler.start();

                mFixtureHandler.stop();
                mFixtureHandler.notifyForm -= new FormNotifyDelegate<PulseCommonHelper.Display>(DisplayMessageToUI);
            });

            nth.Start();

            Log.Debug("toolStripButtonRunScope_Click() Leaved");
        }

        private void toolStripButtonConfig_Click(object sender, EventArgs e)
        {
            mSettingFrom.ShowDialog();
        }

        private void ShowInfo(string info, Color clr)
        {
            this.lbEndMsg.Invoke(new EventHandler(delegate
            {
                this.lbEndMsg.ForeColor = clr;
                this.lbEndMsg.Text = info;
            }));
        }

        private void ShowMsg(string msg, LogMsgType msgType)
        {
            Color _color = (msgType == LogMsgType.ERROR ? Color.Red : msgType == LogMsgType.DEBUG ? Color.Blue : Color.Black);
            if (msgType != LogMsgType.MSG)
                Log.Debug(msg);
            if (rtbMsg.InvokeRequired)
            {
                Action<string> act = (obj) =>
                {
                    rtbMsg.SelectionColor = _color;
                    rtbMsg.AppendText(obj + "\r\n");
                    rtbMsg.ScrollToCaret();
                };
                rtbMsg.Invoke(act, msg);
            }
            else
            {
                rtbMsg.SelectionColor = _color;
                rtbMsg.AppendText(msg + "\r\n");
                rtbMsg.ScrollToCaret();
            }
        }

        /////////////////////////////////////////////////////////////////      
    }
}
